#include "cybertron/core/UtilTime.hpp"
#include "cybertron/core/UtilDirectory.hpp"
#include "cybertron/core/UtilPath.hpp"
#include "cybertron/core/UtilFile.hpp"
#include "cybertron/core/JsonReader.hpp"
#include "../PlatformHeader.hpp"

#include "cybertron/core/UtilCaseResource.hpp"
#include <atomic>
#include <chrono>

#include <iostream>
using namespace std;

CYBERTRON_BEGIN

CybertronCoreAPI  bool UtilCaseResource::InitCaseResourceFile(std::string inputPath)
{
	if (!UtilDirectory::exist(inputPath))
			return false;
	
	std::string caseResourceFile = UtilPath::combine(inputPath, "Settings/agents.json");

	if (!UtilFile::exist(caseResourceFile))
			return false;

	cybertron::json jsonRoot;
	if (!JsonReader::loadFile(jsonRoot, caseResourceFile))
			return false;

	if (JsonReader::hasValue(jsonRoot, "agent_type"))
	{
		nlohmann::json agentTypeValue = JsonReader::getChild(jsonRoot, "agent_type");
		for (auto i = agentTypeValue.begin(); i != agentTypeValue.end(); ++i)
		{
			nlohmann::json agentParameter = JsonReader::getChild(agentTypeValue, i.key());
			CaseResourceItem item ;
			std::string agentTypeKey;
			int assetIdKey;
			agentTypeKey = i.key();
			item.agentType = agentTypeKey;

			for (auto j = agentParameter.begin(); j != agentParameter.end(); ++j)
			{
				if (j.key() == "asset_id")
				{
					assetIdKey = j.value();
					item.assetId = j.value();
				}
				else if (j.key() == "category")
				{
					item.category = JsonReader::toString(j.value());
				}
				else if (j.key() == "UE_blueprint_path")
				{
					item.ueBlueprintPath = JsonReader::toString(j.value());
				}
				else if (j.key() == "length")
				{
					item.length = j.value();
				}
				else if (j.key() == "width")
				{
					item.width = j.value();
				}
				else if (j.key() == "height")
				{
					item.height = j.value();
				}
			}		
			mAgentTypeMap[agentTypeKey] = item;
			mAssetIdMap[assetIdKey] = item;
			memset(&item, 0, sizeof(CaseResourceItem));
		}	
		return true;
	}
	return false;
}

CybertronCoreAPI  CaseResourceItem* UtilCaseResource::getResourceByAgentType(std::string agentType)
{
	AgentTypeMap::iterator item = mAgentTypeMap.find(agentType);
	return &item->second;	
}

CybertronCoreAPI  CaseResourceItem* UtilCaseResource::getResourceByAssetId(int AssetId)
{
	AssetIdMap::iterator item = mAssetIdMap.find(AssetId);
	return &item->second;
}

CYBERTRON_END